import socket,threading,sys
import gnupg,os
from listener import UDPListen

def udpclient(host,port):
    if(not os.path.exists("./gnupg_client")):
        os.mkdir("./gnupg_client")
    if(not os.path.exists("./gnupg_client/private-keys-v1.d")):
        os.mkdir("./gnupg_client/private-keys-v1.d")
    gpg = gnupg.GPG(gnupghome='./gnupg_client')
    gpg.encoding = 'utf-8'
    if (not len(os.listdir('gnupg_client/private-keys-v1.d'))):#check if pkey exists
        key=gpg.gen_key(gpg.gen_key_input(key_type="RSA", key_length=1024))#gen pkey
    public_keys = gpg.list_keys()
    keyid=public_keys[0]['keyid']#get own public key
    ascii_armored_public_key=gpg.export_keys(keyid)#export key

    csocket=socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
    csocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)#allow port reuse
    yourName=input('Enter your name:')
    csocket.sendto(yourName.encode(),((host,int(port))))#send client name
    fromName,address=csocket.recvfrom(1024)#receive server name
    fromName=fromName.decode()#decode server name
    csocket.sendto(ascii_armored_public_key.encode(),((host,int(port))))#send client pubkey
    serverkey,address=csocket.recvfrom(1024)#receive server pubkey
    serverkey=serverkey.decode()#decode server pubkey
    import_server=gpg.import_keys(serverkey)#import server key

    #start listener
    listener=threading.Thread(target=UDPListen,args=(csocket,fromName,gpg,),daemon=True)
    listener.start()
    run=True
    print("Chat started, type /quit or /q to exit")
    while run:
        message=input()
        gpgmsg=str(gpg.encrypt(message,import_server.fingerprints[0],always_trust=True))
        if (message in ["/quit","/q"]):
            run=False
        csocket.sendto(gpgmsg.encode(),address)
    csocket.close()
    sys.exit(0)
